<?php
/**
 * Created by PhpStorm.
 * User: 小灰灰
 * Date: 2022-04-22
 * Time: 16:47:45
 * Info: 写入操作日志中间件
 */

namespace app\admin\middleware;

use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;
use app\common\model\SystemLog as SystemLogModel;

class SystemLog implements MiddlewareInterface
{

    public function process(Request $request, callable $handler): Response
    {
        $adminId = cmf_get_admin_id();
        session()->set('session_admin_id', $adminId);

        $method = strtolower($request->method());
        $params = $request->all();
        if (in_array($method, ['post', 'put', 'delete'])) {
            $url               = $request->url();
            $title             = "";
            $ip                = get_client_ip();
            $data              = [
                'admin_id'    => $adminId,
                'url'         => $url,
                'title'       => $title,
                'method'      => $method,
                'ip'          => $ip,
                'content'     => json_encode($params, JSON_UNESCAPED_UNICODE),
                'create_time' => time(),
            ];
            $admin_log_setting = get_config('admin_log');
            if ($admin_log_setting) {
                SystemLogModel::insert($data);
            }
        }

        return $handler($request);
    }
}
